package com.sky.aion;

import java.io.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @program: aion
 * @description: 索引文件处理类
 * @author: sunzhg
 * @create: 2019-01-20
 **/
public class IndexUtils {

    /**
     *
     * @param indexPath
     * @throws Exception
     */
    public static void writerIndex(final String indexPath,long lastTimeFileSize) {

        final File tmpLogFile = new File(indexPath);
        if (!tmpLogFile.exists()) {
            try {
                tmpLogFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //启动一个线程每60秒钟向日志文件写一次数据
        ScheduledExecutorService exec =
                Executors.newScheduledThreadPool(1);
        exec.scheduleWithFixedDelay(new Runnable() {
            public void run() {
                try {
                    if (tmpLogFile == null) {
                        throw new IllegalStateException("logFile can not be null!");
                    }
                    String index=String.valueOf(lastTimeFileSize);
                    Writer txtWriter = new FileWriter(tmpLogFile, false);
                    System.out.println("写入："+index);
                    txtWriter.write(index);
                    txtWriter.flush();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }, 0, 60, TimeUnit.SECONDS);
    }


    public static long readIndex(final String indexPath)  {

        final File tmpLogFile = new File(indexPath);
        if (!tmpLogFile.exists()) {
            try {
                tmpLogFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            final RandomAccessFile randomFile = new RandomAccessFile(tmpLogFile, "r");
            //启动一个线程每5秒钟向日志文件写一次数据
            randomFile.seek(0);
            String tmp = "";
            while ((tmp =randomFile.readLine()) != null) {
               return Long.parseLong(tmp);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return 0;
    }
}
